<script setup lang="ts">
import {ref} from "vue";
import {UserOutlined} from '@ant-design/icons-vue';
import router from "../router";
import {useAppStore} from "../stores/appStore";

type menuItem = {
  key: string,
  label: string,
  path?: string,
  children?: menuItem[]
}

const menus: menuItem[] = [
  {
    key: 'home',
    label: '首页',
    path: '/'
  }, {
    key: 'sys',
    label: '系统管理',
    children: [
      {
        key: 'user',
        label: '用户管理',
        path: '/users'
      }, {
        key: 'role',
        label: '角色管理',
        path: '/roles'
      }, {
        key: 'resource',
        label: '资源管理',
        path: '/resources'
      }
    ]
  }, {
    key: 'issue-menu',
    label: '问题管理',
    children: [
      {
        key: 'issue-category',
        label: '问题分类管理',
        path: '/issue-categorys'
      }, {
        key: 'issue',
        label: '问题管理',
        path: '/issues'
      }
    ]
  }, {
    key: 'repo',
    label: '知识库管理',
    children: [
      {
        key: 'ebook-category',
        label: '书本分类管理',
        path: '/ebook-categorys'
      }, {
        key: 'ebook',
        label: '书本管理',
        path: '/ebooks'
      }, {
        key: 'doc',
        label: '文档管理',
        path: '/docs'
      }
    ]
  }
]

const selectedKeys2 = ref<string[]>(['1'])
const openKeys = ref<string[]>(['sub1'])

const handleMenuClick = (e: any) => {
  let menusTemp: menuItem[] = menus
  let menu: menuItem | undefined

  const appStore = useAppStore()
  appStore.menuKeyPath.length = 0

  e.keyPath.forEach((key: string) => {
    menu = menusTemp.find(item => key === item.key)
    // 添加到面包屑导航
    appStore.menuKeyPath.push(menu!.label)
    if (menu?.children)
      menusTemp = menu.children
  })
  if (menu?.path) {
    router.push(menu.path)
  }
}
</script>

<template>
  <a-layout-sider width="200" style="background: #fff">
    <a-menu
        v-model:selectedKeys="selectedKeys2"
        v-model:openKeys="openKeys"
        mode="inline"
        :style="{ height: '100%', borderRight: 0 }"
        @click="handleMenuClick"
    >
      <template v-for="(item, index) in menus" :key="index">
        <a-sub-menu v-if="item.children" :key="item.key">
          <template #title>
              <span>
                <user-outlined/>
                {{ item.label }}
              </span>
          </template>
          <a-menu-item v-for="subItem in item.children" :key="subItem.key">
            {{ subItem.label }}
          </a-menu-item>
        </a-sub-menu>

        <a-menu-item v-else :key="item.key">
          {{ item.label }}
        </a-menu-item>
      </template>
    </a-menu>
  </a-layout-sider>
</template>

<style scoped>

</style>